package com.keepc.excel.service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.keepc.excel.component.DataRecordDisruptor;
import com.keepc.excel.domain.DataRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@Service
public class DataImportService {
    // 注入 Disruptor 组件
    @Autowired
    private DataRecordDisruptor dataRecordDisruptor;

    // 数据导入的主要方法，接收文件输入流
    public void importData(InputStream inputStream) {
        EasyExcel.read(inputStream, DataRecord.class, new DataRecordExcelListener(dataRecordDisruptor)).sheet().doRead();
    }

    // EasyExcel 的监听器，用于处理读取到的数据
    public static class DataRecordExcelListener extends AnalysisEventListener<DataRecord> {
        private final DataRecordDisruptor disruptor;

        // 每隔多少条发布事件，然后清理list ，方便内存回收
        private static final int BATCH_COUNT = 10000;
        // 存储数据的批处理列表
        private final List<DataRecord> batch = new ArrayList<>();
        public DataRecordExcelListener(DataRecordDisruptor disruptor) {
            this.disruptor = disruptor;
        }

        @Override
        public void invoke(DataRecord data, AnalysisContext context) {
            // 将读取到的数据添加到批处理列表中
            batch.add(data);
            // 当达到批处理大小，将数据发布到 Disruptor 进行处理
            if (batch.size() >= BATCH_COUNT) {
                disruptor.publish(batch);
                batch.clear();
            }
        }

        @Override
        public void doAfterAllAnalysed(AnalysisContext context) {
            // 处理最后一批数据，确保所有数据都被处理
            if (!batch.isEmpty()) {
                disruptor.publish(batch);
            }
        }
    }
}
